<template>
  <div :class="{ hasTagsView: needTagsView }" class="main-content">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <a-card hoverable>
          <a-flex gap="small" justify="space-between">
            <a-form ref="queryFormRef" :model="queryParams" layout="inline">
              <a-form-item label="用户名称" name="userName">
                <a-input v-model:value="queryParams.userName" allow-clear placeholder="请输入用户名称"
                         @change="handleQuery" @keyup.enter="handleQuery" />
              </a-form-item>
              <a-form-item label="手机号码" name="phonenumber">
                <a-input v-model:value="queryParams.phonenumber" allow-clear placeholder="请输入手机号码"
                         @change="handleQuery" @keyup.enter="handleQuery" />
              </a-form-item>
            </a-form>
            <a-flex justify="end">
              <el-button icon="Search" :loading="loading" round plain type="primary"
                         @click="handleQuery">搜索
              </el-button>
              <el-button icon="RefreshRight" :loading="loading" round
                         @click="resetQuery">重置
              </el-button>
            </a-flex>
          </a-flex>
        </a-card>
      </div>
    </transition>
    <a-card ref="cardRef" class="card-content" hoverable>
      <template #title>
        <el-row ref="headerRef" :gutter="10">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:role:add']" round icon="Plus" plain type="primary" @click="openSelectUser">
              添加用户
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:role:remove']" :disabled="multiple" icon="CircleClose" type="danger"
                      plain round @click="cancelAuthUserAll">
              批量取消授权
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="Close" plain round type="warning" @click="handleClose">关闭</el-button>
          </el-col>
<!--          <right-toolbar v-model:showSearch="showSearch" :search="true" @query-table="getList"></right-toolbar>-->
        </el-row>
      </template>
      <a-spin :spinning="loading" size="large">
        <el-table :data="userList" :height="tableHeight" @selection-change="handleSelectionChange">
          <el-table-column align="center" type="selection" min-width="55" />
          <el-table-column align="center" label="序号" type="index" min-width="50">
            <template #default="scope">
              <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" align="center" label="用户名称" min-width="150"
                           prop="userName" />
          <el-table-column :show-overflow-tooltip="true" align="center" label="用户昵称" min-width="150"
                           prop="nickName" />
          <el-table-column :show-overflow-tooltip="true" align="center" label="邮箱" min-width="150" prop="email" />
          <el-table-column :show-overflow-tooltip="true" align="center" label="手机" min-width="150"
                           prop="phonenumber" />
          <el-table-column align="center" label="状态" min-width="80" prop="status">
            <template #default="scope">
              <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="创建时间" prop="createTime" width="180">
            <template #default="scope">
              <span>{{ scope.row.createTime }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" min-width="80">
            <template #default="scope">
              <el-tooltip content="取消授权" placement="top">
                <el-button v-hasPermi="['system:role:remove']" circle icon="CircleClose" type="danger"
                           @click="cancelAuthUser(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </a-spin>
      <select-user ref="selectRef" :role-id="queryParams.roleId" @ok="handleQuery" />
    </a-card>
    <a-card hoverable ref="paginationRef" v-show="total>0">
      <pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                  :total="total" @pagination="getList" />
    </a-card>
  </div>
</template>

<script setup name="AuthUser" lang="ts">
import { allocatedUserList, authUserCancel, authUserCancelAll } from '@/api/system/role';
import { UserQuery } from '@/api/system/user/types';
import { UserVO } from '@/api/system/user/types';
import SelectUser from './selectUser.vue';
import { RouteLocationNormalized } from 'vue-router';

import { useElTableHeight } from '@/utils/useElTableHeight';
import useSettingsStore from '@/store/modules/settings';
import { ReloadOutlined, SearchOutlined } from '@ant-design/icons-vue';

const settingsStore = useSettingsStore();
const needTagsView = computed(() => settingsStore.tagsView);
/*计算表格高度*/
const cardRef = ref<HTMLElement | null>(null);
const headerRef = ref<any>(null);
const paginationRef = ref<any>(null);
const { tableHeight } = useElTableHeight(cardRef, [headerRef, paginationRef]);


const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

const userList = ref<UserVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const multiple = ref(true);
const total = ref(0);
const userIds = ref<Array<string | number>>([]);

const queryFormRef = ref<ElFormInstance>();
const selectRef = ref<InstanceType<typeof SelectUser>>();

const queryParams = reactive<UserQuery>({
  pageNum: 1,
  pageSize: 20,
  roleId: route.params.roleId as string,
  userName: undefined,
  phonenumber: undefined
});

/** 查询授权用户列表 */
const getList = async () => {
  loading.value = true;
  const res = await allocatedUserList(queryParams);
  userList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
// 返回按钮
const handleClose = () => {
  const obj: RouteLocationNormalized = {
    path: '/system/role',
    fullPath: '',
    hash: '',
    matched: [],
    meta: undefined,
    name: undefined,
    params: undefined,
    query: undefined,
    redirectedFrom: undefined
  };
  proxy?.$tab.closeOpenPage(obj);
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
// 多选框选中数据
const handleSelectionChange = (selection: UserVO[]) => {
  userIds.value = selection.map((item) => item.userId);
  multiple.value = !selection.length;
};
/** 打开授权用户表弹窗 */
const openSelectUser = () => {
  selectRef.value?.show();
};
/** 取消授权按钮操作 */
const cancelAuthUser = async (row: UserVO) => {
  await proxy?.$modal.confirm('确认要取消该用户"' + row.userName + '"角色吗？');
  await authUserCancel({ userId: row.userId, roleId: queryParams.roleId });
  await getList();
  proxy?.$modal.notifySuccess('取消授权成功');
};
/** 批量取消授权按钮操作 */
const cancelAuthUserAll = async () => {
  const roleId = queryParams.roleId;
  const uIds = userIds.value.join(',');
  await proxy?.$modal.confirm('是否取消选中用户授权数据项?');
  await authUserCancelAll({ roleId: roleId, userIds: uIds });
  await getList();
  proxy?.$modal.notifySuccess('取消授权成功');
};

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped></style>
